#pragma once


#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <baseClass/Texture2D.h>
#include <baseClass/Shader.h>
#include <baseClass/Picture.h>


namespace UI
{
    

class Canvas2D
{    
private:
    uint32_t VAO;
    uint32_t VBO;

    

    uint32_t Width = 0;
    uint32_t Height = 0;

   
    const string vertexShaderSource = R"(
        #version 330 core
        layout(location = 0) in vec2 position;

        out vec2 texCoord;
        void main()
        {
            gl_Position = vec4(position,0.0 ,1.0);
            texCoord = (position + 1) / 2.0;
        }
    )";
    const string fragmentShaderSource = R"(
        #version 330 core
        in vec2 texCoord;
        out vec4 fragColor;
        uniform sampler2D textureImage;
        void main()
        {
            fragColor = texture(textureImage, texCoord);
            if(fragColor.a == 0.0) discard;
        }
    )";
 

    static Shader * pictureShader;

    Texture2D  texture;

    bool IsChangeTexture = false;

    Picture picture;
public:
    Canvas2D(int SCR_WIDTH, int SCR_HEIGHT): Width(SCR_WIDTH), Height(SCR_HEIGHT),picture(SCR_WIDTH, SCR_HEIGHT,4,GL_RGBA)
    {
        if(pictureShader == nullptr)
            pictureShader = new Shader(vertexShaderSource, fragmentShaderSource);

        float vertices[] = { 
            -1.f, -1.f, 
             1.f, -1.f, 
             1.f,  1.f, 

            -1.f,  1.f,
             1.f,  1.f, 
            -1.f, -1.f
 
        };
        glGenVertexArrays(1, &VAO);
        glGenBuffers(1, &VBO);
       

        glBindVertexArray(VAO);
        glBindBuffer(GL_ARRAY_BUFFER, VBO);
        glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

        glEnableVertexAttribArray(0);
        glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0);
        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glBindVertexArray(0);
    }


    void DrawPicture(Picture& Picture, int x, int y, int width, int height)
    {
        // TODO: implement this function
        texture.UpdataPic(Picture);
    }


    void Rander()
    {
        texture.bind(0,GL_CLAMP_TO_BORDER, GL_CLAMP_TO_BORDER, GL_LINEAR, GL_LINEAR);
        glBindVertexArray(VAO);
        glDrawArrays(GL_TRIANGLES, 0, 6);
        glBindVertexArray(0);
    }


    ~Canvas2D()
    {
        glDeleteVertexArrays(1, &VAO);
        glDeleteBuffers(1, &VBO);
    }
};

Shader * Canvas2D::pictureShader = nullptr;


} // namespace UI